package test.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class GetMethod {

  /**
   * @param args
   * @throws IOException
   * @throws ClientProtocolException
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    HttpClient httpclient = new DefaultHttpClient();
    try {
      String keyword = null;

      if (args.length == 0) {
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter keyword: ");
        keyword = console.readLine();
      } else {
        keyword = args[0];
      }

      HttpGet httpget = new HttpGet(
          "http://localhost:8080/demo.servlet/servlet/HttpClientTest?txtKeyword=" + keyword);

      System.out.println("executing request " + httpget.getURI());

      // Create a response handler
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String responseBody = httpclient.execute(httpget, responseHandler);

      System.out.println("----------------------------------------");

      System.out.println(responseBody);

      System.out.println("----------------------------------------");
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpclient.getConnectionManager().shutdown();
    }
  }

}
